import React, { Component } from 'react';

import { onTouchEnd } from '../../main/global';

import S from './index.m.less';

const onTap = onTouchEnd;

const KEY = [
    [1, 'ABC'],
    [2, 'ABC'],
    [3, 'DEF'],
    [4, 'GHI'],
    [5, 'JKL'],
    [6, 'MNO'],
    [7, 'PQRS'],
    [8, 'TUV'],
    [9, 'WXYZ'],
];

function formartPrice(numStr = '') {
    return numStr
        .replace(/^0+/, '0') // 只允许输入单个0
        .replace(/^0+([1-9].*)/, '$1') // 去除012的前置0
        .replace(/^\.*/, ''); // 清楚前置点
}

export default class InputNum extends Component {
    static defaultProps = {
        title: '', // 输入文案提示
        doneTitle: '完成',
        dott: false,
        dottLen: 2,
        filterDott: true, // 过滤点，只允许一个点出现
        maxLen: undefined,
        max: undefined,
        min: undefined,
        onInput: () => {},
        onChange: () => {},
        onDone: () => {},
        type: '', // price 对价格进行格式化处理
        hideBottomLeft: false, // 取消左下角的按键
        isReplace: false,
        showXButton: false, // 左下角显示 X 按钮 用于身份证输入
        showCancel: false, // 左下角显示取消按钮
        onCancel: () => {}, // 取消按钮回调
    };

    constructor(props) {
        super(props);
        this.state = {
            num: `${this.props.defaultValue || ''}`,
        };
    }

    componentDidMount() {
        $(window).on('keyup', this.handleKeyUp);
        $(window).on('keydown', this.handleKeyDown);
    }

    componentWillUnmount() {
        $(window).off('keyup', this.handleKeyUp);
        $(window).off('keydown', this.handleKeyDown);
    }

    handleKeyUp = (event) => {
        const code = event.keyCode;
        if (code >= 48 && code <= 57) {
            if (this.props.isReplace) {
                return this.replace(code - 48);
            }
            return this.add(code - 48);
        }

        // esc
        if (code == 27) {
            return this.done();
        }

        // enter
        if (code == 13) {
            return this.done();
        }
        return null;
    };

    // 连续删除功能
    handleKeyDown = (event) => {
        const code = event.keyCode;
        // delete
        if (code == 8) {
            return this.delete();
        }
        return null;
    };

    handleSoftKeyClick = (num) => () => {
        if (this.props.isReplace) {
            this.replace(num);
            return;
        }
        this.add(num);
    };

    replace = (num) => {
        // eslint-disable-next-line react/no-direct-mutation-state
        this.state.num = `${num}`;
        this.triggerCallback(this.state.num);
    };

    add(num) {
        // 只允许出现一个小数点
        if (this.props.filterDott && num == '.' && `${this.state.num}`.includes('.')) {
            return;
        }
        // eslint-disable-next-line react/no-direct-mutation-state
        this.state.num += `${num}`;
        this.triggerCallback(this.state.num);
    }

    triggerCallback(value) {
        const { max, maxLen, dottLen, type, min } = this.props;
        const { state } = this;

        // 最大值比较
        if (max !== undefined && /^[\d.]+$/.test(max)) {
            if (Number(value) > max) {
                value = `${max}`;
            }
            state.num = value;
        }

        // 最大值比较
        if (min !== undefined && /^[\d.]+$/.test(min)) {
            if (Number(value) < min) {
                value = `${min}`;
            }
            state.num = value;
        }

        // 最大长度
        if (maxLen) {
            value = value.slice(0, maxLen);
            state.num = value;
        }

        // 小数点后面个数
        if (dottLen) {
            state.num = state.num.replace(/\.[0-9]*/, ($0) => $0.slice(0, 1 + dottLen));
        }

        // 如果类型为price，则对价格进行格式化
        if (type === 'price') {
            state.num = formartPrice(state.num);
        }

        // onInput的返回值如果存在，就作为最新的num
        const returnValue = this.props.onInput(state.num);
        state.num = returnValue !== undefined ? returnValue : state.num;

        this.props.onChange(state.num);
    }

    delete = () => {
        const { state } = this;
        state.num = `${state.num}`.slice(0, -1);
        this.triggerCallback(state.num);
    };

    done = () => {
        const { onDone } = this.props;
        this.props.close();
        onDone && onDone();
    };

    cancel = () => {
        const { onCancel, close } = this.props;
        close && close();
        onCancel && onCancel();
    };

    deleteTap = () => {
        let isPhone = !(!$.os.phone || (window.webkit && window.webkit.messageHandlers)); // 非手机 click
        if ($.os.ios) {
            isPhone = true;
        }
        if (isPhone) {
            return {
                onTouchStart: () => {
                    this.interval && clearInterval(this.interval);
                    this.interval = setInterval(this.delete, 140);
                },
                onTouchEnd: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    clearInterval(this.interval);
                    this.delete();
                },
            };
        }
        return {
            onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.delete();
            },
        };
    };

    // 左下角按钮
    renderBottomLeftBtn = () => {
        const { dott, hideBottomLeft, showCancel, showXButton } = this.props;
        if (hideBottomLeft) return <li className={S.othernum} />;
        if (showCancel) {
            return (
                <li
                    className={S.othernum}
                    style={{ fontSize: '20px' }}
                    {...onTap(this.cancel, 1, true)}
                    data-touch="touchEffect"
                >
                    取消
                </li>
            );
        }
        if (showXButton) {
            return (
                <li
                    className={S.othernum}
                    style={{ backgroundColor: '#ffffff' }}
                    {...onTap(() => this.add('X'), 1, true)}
                    data-touch="touchEffect"
                >
                    X
                </li>
            );
        }
        return (
            <li
                className={S.othernum}
                {...onTap(this.handleSoftKeyClick(dott ? '.' : '00'), 1, true)}
                data-touch="touchEffect"
            >
                {dott ? '.' : '00'}
            </li>
        );
    };

    render() {
        const { title, doneTitle } = this.props;

        return (
            <div className={S.fixednumMain}>
                <div className={S.tipBanner}>
                    <span className={S.title}>
                        <span>{title}</span>
                    </span>
                    <div className={S.finish} {...onTap(this.done)}>
                        {doneTitle}
                    </div>
                </div>
                <div
                    className={S.numkey}
                    onContextMenu={(e) => {
                        e.preventDefault();
                    }}
                >
                    <ul>
                        {KEY.map((item, index) => {
                            const [num, bottom] = item;
                            return (
                                <li
                                    key={index}
                                    {...onTap(this.handleSoftKeyClick(num), 1, true)}
                                    data-touch="touchEffect"
                                >
                                    <div>{num}</div>
                                    <span style={{ opacity: num == 1 && '0' }}>{bottom}</span>
                                </li>
                            );
                        })}
                        {this.renderBottomLeftBtn()}
                        <li className={S.zero} {...onTap(this.handleSoftKeyClick(0), 1, true)} data-touch="touchEffect">
                            0
                        </li>
                        <li className={S.delete} {...onTap(this.delete, 1, true)} data-touch="touchEffect" />
                    </ul>
                </div>
            </div>
        );
    }
}
